package com.cheer.controller;

import com.cheer.dto.ForgetPasswordDTO;
import com.cheer.dto.RegisterDTO;
import com.cheer.security.UserInfoHolder;
import com.cheer.service.AuthService;
import com.cheer.service.OrganizationService;
import com.cheer.vo.AccountVO;
import com.cheer.vo.OrganizationTreeVO;
import com.cheer.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 身份认证API
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserInfoHolder userInfoHolder;

    /**
     * 获取验证码
     */
    @GetMapping("/captcha")
    public void getCaptcha(@RequestParam(required = false) Integer width,
                           @RequestParam(required = false) Integer height,
                           @RequestParam Integer type) {
        authService.getCaptcha(width, height, type);
    }

    /**
     * 查询组织机构
     */
    @GetMapping("/organization")
    public Result<List<OrganizationTreeVO>> getOrganization() {
        List<OrganizationTreeVO> treeList = organizationService.listRegisteredOrganizations();
        return Result.success(treeList);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result<Void> register(@RequestBody @Valid RegisterDTO registerDTO) {
        authService.register(registerDTO);
        return Result.success();
    }

    /**
     * 忘记密码获取验证问题
     */
    @GetMapping("/question")
    public Result<String> getQuestion(@RequestParam String account) {
        String question = authService.getQuestion(account);
        return Result.success(question);
    }

    /**
     * 重设密码
     */
    @PostMapping("/password")
    public Result<Void> updatePassword(@RequestBody @Valid ForgetPasswordDTO forgetPasswordDTO) {
        authService.updatePassword(forgetPasswordDTO);
        return Result.success();
    }

    /**
     * 登录是否需要验证码
     */
    @GetMapping("/required")
    public Result<Boolean> isCaptchaRequired() {
        Boolean required = authService.isLoginCaptchaRequired();
        return Result.success(required);
    }

    /**
     * 查询账号信息
     */
    @GetMapping("/account")
    public Result<AccountVO> getAccount() {
        AccountVO accountVO = authService.getAccount(userInfoHolder.getAccountId());
        return Result.success(accountVO);
    }
}
